﻿#include "log_tool.h"

LogTool *LogTool::_instance = nullptr;

// 单例模式获取实例
LogTool *LogTool::getInstance()
{
    static std::mutex instanceMutex;
    std::lock_guard<std::mutex> lock(instanceMutex);
    if (!_instance)
    {
        _instance = new LogTool();
    }
    return _instance;
}

LogTool::LogTool():_currentLevel(LogLevel::LOG_LEVEL_DEBUG)
{

}

LogTool::~LogTool()
{
    if (_logFile.is_open())
    {
        _logFile.close();
    }
}

// 设置日志级别, 末尾一定要加/
void LogTool::init(const std::string &path, LogLevel level)
{
    std::string file_name = path + "mengyu_wubi.log";
    _logFile.open(file_name,
                 std::ios::out);
    _currentLevel = level;
}

// 日志记录核心方法
void LogTool::log(LogLevel level, const char *format, ...)
{
    if (level < _currentLevel)
        return;

    std::lock_guard<std::mutex> lock(_logMutex);

    // 获取当前时间
    time_t now = time(0);
    tm ltm;
    localtime_s(&ltm, &now);

    // 格式化日志前缀
    char timeStr[20];
    strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", &ltm);

    const char *levelStr = "";
    switch (level)
    {
    case LogLevel::LOG_LEVEL_DEBUG:
        levelStr = "DEBUG";
        break;
    case LogLevel::LOG_LEVEL_INFO:
        levelStr = "INFO";
        break;
    case LogLevel::LOG_LEVEL_WARNING:
        levelStr = "WARNING";
        break;
    case LogLevel::LOG_LEVEL_ERROR:
        levelStr = "ERROR";
        break;
    }

    // 构造完整日志信息
    va_list args;
    va_start(args, format);
    char message[4096];
    vsnprintf(message, sizeof(message), format, args);
    va_end(args);

    // 输出日志
    std::string logEntry = std::string(timeStr) + " [" + levelStr + "] " + message + "\n";

    // 控制台输出
    //std::cout << logEntry;

    // 文件输出
    if (_logFile.is_open())
    {
        _logFile << logEntry;
        _logFile.flush();
    }
}
